
import React from 'react'
import {connect} from "react-redux";
import {messages} from "share/common";
import {Button, Form, Icon, Input, message, Modal, Popover, Spin, Tag, Tooltip} from "antd";
const { CheckableTag } = Tag;
const { TextArea } = Input;
const FormItem = Form.Item;
import httpFetch from 'share/httpFetch'
import baseService from "share/base.service";
import ImageUpload from "components/image-upload";
import 'styles/components/template/quick-reply.scss'
import config from 'config'

class QuickReply extends React.Component {

  state = {
    loading: false,
    popoverVisible: false,
    errorType: '',
    quickTags: [],
    reason: '',
    fastReplyChosen: [],
    honestEvent: []
  };

  componentWillMount() {
    this.getQuickTags();
    if( 'value' in this.props){
      this.setState({ reason: this.props.value });
    }
  }

  componentDidMount() {
    const { onRef } = this.props;
    onRef && onRef(this);
  }

  componentWillReceiveProps(nextProps) {
    if( 'value' in nextProps){
      this.setState({
        reason: nextProps.value
      });
    }
  }

  //popover的visible控制
  handleVisibleChange = (visible) => {
    this.setState({ popoverVisible: visible });
  };

  //关闭popover
  handleClosePopover = () => {
    this.setState({ popoverVisible: false });
  };

  handleFastReplyEdit =() => {
    let fastReplyEdit = this.state.fastReplyEdit;
    this.setState({ fastReplyEdit: !fastReplyEdit })
  };

  //获取快捷回复内容
  getQuickTags = () => {
    const { audit } = this.props.params;
    this.setState({ loading: true }, () => {
      let url=`${config.baseUrl}/api/quick/reply`;
      if(audit){
        url=`${config.baseUrl}/api/audit/quick/reply?userOid=${this.props.loginUser.userOID}`;
      }
      httpFetch.get(url).then(res => {
        if(res.status === 200) {
          let tags = audit ? res.data.rows : res.data;
          this.setState({ quickTags: tags, loading: false })
        }
      })
    });
  };

  //显示新增快捷回复输入框
  showTagInput = () => {
    this.setState({ inputVisible: true });
  };

  //关闭新增快捷回复输入框
  closeInputModal = () => {
    this.setState({ inputVisible: false, popoverVisible: true });
  };

  //确认新增的快捷回复
  handleInputConfirm = () => {
    const { audit } = this.props.params;
    let values = this.props.form.getFieldsValue();
    if (values.quickReplyTxt) {
      if(values.quickReplyTxt.trim() && values.quickReplyTxt.trim().length <= 500) {
        this.setState({ loading: true });
        let url=`${config.baseUrl}/api/quick/reply`;
        let param = {reply: values.quickReplyTxt.trim()};
        if(audit){
          url=`${config.baseUrl}/api/audit/quick/reply`;
          param={
            reply: values.quickReplyTxt.trim(),
            tenantId: this.props.company.tenantId,
            type: 2000,
            status: 1000,
            setOfBooksId: this.props.company.setOfBooksId,
            userOid: this.props.loginUser.userOID
          };
        }
        httpFetch.post(url, param).then(res => {
          if(res.status === 200) {
            this.props.form.setFieldsValue({ quickReplyTxt: '' });
            this.closeInputModal();
            this.getQuickTags();
            message.success(messages('common.operate.success')/*操作成功*/);
          }
        }).catch(() => {
          this.setState({ loading: false });
          message.error(messages('common.error1')/*获取数据失败，请稍后重试或联系管理员*/);
        });
      } else {
        message.error(messages('common.max.characters.length',{arg1: 500})/*最多输入{arg1}个字符*/);
      }
    } else {
      message.error(messages('common-1.key225')/*请输入temp2*/);
    }
  };

  //删除快捷回复标签
  handleDeleteTag = (e, item) => {
    e.stopPropagation();
    const { audit } = this.props.params;
    this.setState({ loading: true });
    let url=`${config.baseUrl}/api/quick/reply`;
    let param = {quickReplyOIDs: item.quickReplyOID};
    if(audit){
      url=`${config.baseUrl}/api/audit/quick/reply`;
      param = {id: item.id };
    }
    httpFetch.delete(url, param).then(res => {
      let isSuccess = audit ? res.data.rows : true;
      if(res.status === 200 && isSuccess) {
        this.getQuickTags();
        message.success(messages('common.delete.success',{arg1: ''})/*{arg1} 删除成功*/)
      }else{
        this.setState({ loading: false });
        message.error(messages('common.operate.filed')/*操作失败*/)  //操作失败
      }
    }).catch(e => {
      this.setState({ loading: false });
      message.success(`${messages('common.operate.filed')/*操作失败*/}，${e.response.data.message}`)
    })
  };

  //选择快捷回复
  onFastReplyChange = (checked, replyId) => {
    let { quickTags, fastReplyChosen, honestEvent, reason } = this.state;
    const { onChange, afterSelectTag } = this.props;
    let fastReplyChosenValue = [];
    if (reason) {
      fastReplyChosenValue = reason.split('，')
    }
    quickTags.map(item => {
      if (item.id === replyId) {
        item.checked = true;
        fastReplyChosen.push(item);
        fastReplyChosenValue.push(item.reply)
      }
    });
    onChange && onChange(fastReplyChosenValue.join('，'));
    const { needHonest, applicantOID } = this.props.params;
    this.setState({
      reason: fastReplyChosenValue.join('，'),
      fastReplyChosen
    }, () => {
      if(needHonest) {
        let params = { replyId, applicantOID };
        baseService.getHonestEvent(params).then(res => {
          res.data.id && honestEvent.filter(item => item.id === res.data.id).length === 0 && honestEvent.push(res.data);
          afterSelectTag && afterSelectTag(honestEvent);
        });
      } else {
        afterSelectTag && afterSelectTag();
      }
    })
  };

  handleImageUpload = (attachments) => {
    const { handleImageUpload } = this.props;
    handleImageUpload && handleImageUpload(attachments);
  };

  clearData = () => {
    const { onChange, afterChange } = this.props;
    this.imageUploadRef && this.imageUploadRef.clearImageList();
    this.setState({
      reason: ''
    }, () => {
      onChange && onChange('');
      afterChange && afterChange();
    });
  };

  onChangeReason = e => {
    const { onChange, afterChange } = this.props;
    this.setState({
      reason: e.target.value
    }, () => {
      onChange && onChange(this.state.reason);
      afterChange && afterChange();
    });
  };

  render() {
    const { withAttachments, audit } = this.props.params;
    const { getFieldDecorator } = this.props.form;
    const {
      loading, quickTags = [], fastReplyEdit, inputVisible, reason, popoverVisible, replyKey
    } = this.state;

    const fastReplyTitle = (
      <div className="quick-reply-title">
        {messages('common-1.key441')/*快捷回复*/}
        <div className='info-message'>
          <Icon type='info-circle' />
          {messages('common-1.key442')/*管理员定义的快捷回复不可删除*/}
        </div>
        <Icon type="close" className="edit" style={{fontSize: 21, marginLeft: 10, cursor: 'pointer'}} onClick={this.handleClosePopover} />
      </div>
    );
    const fastReplyContent = (
      <div className="quick-reply-content">
        <Spin spinning={loading}>
          <div className='quick-reply-topline'>
            <Input
              value={replyKey}
              size="small"
              onChange={e => this.setState({ replyKey: e.target.value })}
              className='quick-reply-search'
              placeholder={messages('common-1.key443')/*搜索快捷回复...*/}
            />
            {
              !inputVisible && !fastReplyEdit && <Button
                size="small"
                type="link"
                icon="plus"
                className="edit"
                onClick={this.showTagInput}
              >
                {messages('common-1.key444')/*新增*/}
              </Button>
            }
            <Button
              size="small"
              type="link"
              icon={!fastReplyEdit && "delete"}
              className="edit"
              onClick={this.handleFastReplyEdit}
            >
              {!fastReplyEdit ? messages('common.delete')/*删除*/ : messages('common-1.key415')/*完成*/}
            </Button>
          </div>
          <div className='quick-reply-list'>
            {quickTags.filter(item => !replyKey || item.reply.indexOf(replyKey) > -1).map(item => {
              let isEditItem = (item.type !== 2002 && !audit) || item.levelCode === 'USER'; //审批意见按type处理，审核意见按levelCode处理
              return (
                <CheckableTag
                  key={item.id}
                  className={`quick-reply-tag ${fastReplyEdit && !isEditItem && 'disable-edit'}`}
                  color="#000000"
                  onChange={(checked) => this.onFastReplyChange(checked, item.id)}
                >
                  {item.reply.length > 15 ? <Tooltip title={item.reply}>{item.reply.substr(0, 15)}…</Tooltip> : item.reply}
                  {
                    fastReplyEdit &&
                    isEditItem &&
                    <a className="delete-tag" onClick={e => this.handleDeleteTag(e, item)}>&times;</a>
                  }
                </CheckableTag>)
            })}
          </div>
        </Spin>
      </div>
    );

    return (
      <div className="quick-reply" >
        {withAttachments &&
          <ImageUpload
            className="bar-image-upload"
            attachmentType="EXP_REPORT"
            maxNum={3}
            fileType={['jpg', 'jpeg', 'bmp', 'gif', 'png']}
            onChange={this.handleImageUpload}
            onRef={ref => this.imageUploadRef = ref}
          />
        }
        <Popover
          trigger="click"
          placement="topLeft"
          title={fastReplyTitle}
          content={fastReplyContent}
          visible={popoverVisible}
          onVisibleChange={this.handleVisibleChange}
          autoAdjustOverflow={true}
          getPopupContainer={triggerNode => triggerNode.parentNode}
          overlayStyle={{
            width: 420
          }}
        >
          <div>
            {React.cloneElement(
              this.props.children,
              {
                value: reason,
                onChange: this.onChangeReason
              }
            )}
          </div>
        </Popover>
        <Modal
          title={messages('common-1.key445')/*新增快捷回复*/}
          visible={inputVisible}
          onCancel={this.closeInputModal}
          maskClosable={false}
          destroyOnClose={true}
          footer={[
            <Button key="back" onClick={this.closeInputModal}>{messages('common.cancel')/*取消*/}</Button>,
            <Button key="submit" htmlType="submit" type="primary" loading={loading} onClick={this.handleInputConfirm}>{messages('common.ok')/*确定*/}</Button>
          ]}
        >
          <Form>
            <FormItem>
              {getFieldDecorator('quickReplyTxt', {
                initialValue: ''
              })(
                <TextArea placeholder={messages('common.max.characters.length',{arg1: 500})/*最多输入{arg1}个字符*/}
                          rows={6}
                          style={{resize: 'none'}}/>
              )}
              <div style={{textAlign: 'right'}}>
                {this.props.form.getFieldValue('quickReplyTxt').trim().length} / 500
              </div>
            </FormItem>
          </Form>
        </Modal>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    loginUser: state.login.loginUser,
    company: state.login.company
  }
}

const wrappedQuickReply = Form.create()(QuickReply);
export default connect(mapStateToProps)(wrappedQuickReply)
